package browser;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @description:
 * @author: 张德长 dechang.zhang@ucarinc.com
 * @date: 10:29:02 2018/11/27
 * @version:2.0
 */
public class Chorme {
    public static int windowWidth = 1920;
    public static int windowHeight = 1080;
    public static String chromeDriverPath = "src\\\\main\\\\java\\\\browser\\\\chromedriver.exe";

    /***
     * 打开浏览器
     **/
    public static WebDriver open(int windowWidth, int windowHeight, boolean show) {
        //隐藏浏览器的启动
        ChromeOptions options = new ChromeOptions();
        if (!show) {
            options.addArguments("--headless");
            options.addArguments("--disable-gpu");
        }
        //chromedriver服务地址
        System.setProperty("webdriver.chrome.driver", chromeDriverPath);
        WebDriver driver = new ChromeDriver(options);
        Dimension dimension = new Dimension(windowWidth, windowHeight);
        driver.manage().window().setSize(dimension);
        return driver;
    }

    /***
     * 切换浏览器选项卡
     **/
    public static WebDriver changeWindow(int index, WebDriver driver) {
        String[] handles = new String[driver.getWindowHandles().size()];
        driver.getWindowHandles().toArray(handles);
        WebDriver handle1 = driver.switchTo().window(handles[index]);
        Dimension dimension = new Dimension(windowWidth, windowHeight);
        handle1.manage().window().setSize(dimension);
        return handle1;
    }

    /**
     * 网页快照
     **/
    public static File snapshot(WebDriver driver, boolean save) {
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        /**
         * 截屏操作
         * 图片已当前时间命名
         */
        if (save) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String time = dateFormat.format(Calendar.getInstance().getTime());
            try {
                FileUtils.copyFile(srcFile, new File("屏幕截图", time + ".png"));
                //利用FileUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件;"屏幕截图"即时保存截图的文件夹
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return srcFile;
    }


}
